package com.zhuhjay.common.redis.util;

import com.zhuhjay.common.base.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

/**
 * @author ZhuHJay
 * @date 2023/10/12 9:16
 */
@Slf4j
public class RedissonUtils {

    private static final RedissonClient REDISSON_CLIENT;
    static {
        REDISSON_CLIENT = SpringContextHolder.getBean(RedissonClient.class);
    }

    /**
     * 分布式锁: 快速失败尝试加锁, 拿不到锁就退出, 不等待
     * @param lockKey 锁的key
     * @param runnable 业务逻辑
     * @return 是否获取锁
     */
    public static boolean withFastFailTryLock(String lockKey, Runnable runnable) {
        log.info("[FastFailTryLock -> <{}>]尝试获取锁", lockKey);
        RLock lock = REDISSON_CLIENT.getLock(lockKey);
        if (!lock.tryLock()) {
            log.info("[FastFailTryLock -> <{}>]获取锁失败", lockKey);
            return false;
        }
        try {
            runnable.run();
            return true;
        } finally {
            lock.unlock();
            log.info("[FastFailTryLock -> <{}>]释放锁", lockKey);
        }
    }

    /**
     * 分布式锁: 无限等待加锁, 拿不到锁就一直等待
     * @param lockKey 锁的key
     * @param runnable 业务逻辑
     */
    public static void withInfiniteWaitLock(String lockKey, Runnable runnable) {
        log.info("[InfiniteWaitLock -> <{}>]尝试获取锁", lockKey);
        RLock lock = REDISSON_CLIENT.getLock(lockKey);
        lock.lock();
        try {
            runnable.run();
        } finally {
            lock.unlock();
            log.info("[InfiniteWaitLock -> <{}>]释放锁", lockKey);
        }
    }

}